resource "google_kms_key_ring" "keyring" {
  name     = "keyring-example"
  location = "global"
}

resource "google_kms_crypto_key" "cryptokey" {
  name            = "crypto-key-example"
  key_ring        = google_kms_key_ring.keyring.id
  rotation_period = "100000s"

  lifecycle {
    prevent_destroy = true
  }
}

resource "google_kms_secret_ciphertext" "<%= ctx[:primary_resource_id] %>" {
  crypto_key = google_kms_crypto_key.cryptokey.id
  plaintext  = "my-secret-password"
}

resource "google_compute_instance" "instance" {
  name         = "<%= ctx[:vars]['instance_name'] %>"
  machine_type = "e2-medium"
  zone         = "us-central1-a"

  boot_disk {
    initialize_params {
      image = "debian-cloud/debian-9"
    }
  }

  network_interface {
    network = "default"

    access_config {
    }
  }

  metadata = {
    password = google_kms_secret_ciphertext.<%= ctx[:primary_resource_id] %>.ciphertext
  }
}
